"""扫描问题API"""
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query, Body
from sqlalchemy.orm import Session

from app.database import get_db
from app.services.issue_service import IssueService
from app.schemas.issue import IssueResponse, IssueConfirmRequest
from app.schemas.common import ResponseBase, PaginatedResponse

router = APIRouter()


@router.get("/records/{record_id}/issues", response_model=PaginatedResponse[IssueResponse])
async def get_issues_by_record(
    record_id: int,
    level: Optional[str] = Query(None, description="问题级别"),
    confirm_status: Optional[str] = Query(None, description="确认状态"),
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    order_by: Optional[str] = Query(None, description="排序字段"),
    db: Session = Depends(get_db),
):
    """根据扫描记录ID获取问题列表"""
    service = IssueService(db)

    # 构建过滤条件
    filters = {}
    if level:
        filters["level"] = level
    if confirm_status:
        filters["confirm_status"] = confirm_status

    issues = service.get_by_record_id(
        record_id=record_id,
        skip=skip,
        limit=limit,
        filters=filters if filters else None,
        order_by=order_by,
    )

    # 获取扩展字段数据
    issue_responses = []
    for issue in issues:
        issue_dict = IssueResponse.from_orm(issue).dict()
        # 获取扩展字段
        extensions = service.get_extensions(issue.id)
        issue_dict["extension_data"] = extensions if extensions else None
        issue_responses.append(IssueResponse(**issue_dict))

    total = service.count_by_record_id(record_id)

    return PaginatedResponse(
        code=200,
        message="success",
        data=issue_responses,
        total=total,
        skip=skip,
        limit=limit,
    )


@router.get("/{issue_id}", response_model=ResponseBase)
async def get_issue(
    issue_id: int,
    db: Session = Depends(get_db),
):
    """获取问题详情"""
    service = IssueService(db)
    issue = service.get_by_id(issue_id)

    if not issue:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"问题 {issue_id} 不存在",
        )

    issue_dict = IssueResponse.from_orm(issue).dict()
    # 获取扩展字段
    extensions = service.get_extensions(issue_id)
    issue_dict["extension_data"] = extensions if extensions else None

    return ResponseBase(
        code=200,
        message="success",
        data=IssueResponse(**issue_dict),
    )


@router.post("/{issue_id}/confirm", response_model=ResponseBase)
async def confirm_issue(
    issue_id: int,
    request: IssueConfirmRequest = Body(...),
    db: Session = Depends(get_db),
):
    """确认问题"""
    service = IssueService(db)
    issue = service.confirm_issue(
        issue_id=issue_id,
        confirm_type=request.confirm_type,
        confirmed_by=request.confirmed_by,
        confirm_comment=request.confirm_comment,
    )

    if not issue:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"问题 {issue_id} 不存在",
        )

    issue_dict = IssueResponse.from_orm(issue).dict()
    extensions = service.get_extensions(issue_id)
    issue_dict["extension_data"] = extensions if extensions else None

    return ResponseBase(
        code=200,
        message="问题确认成功",
        data=IssueResponse(**issue_dict),
    )


@router.post("/batch-confirm", response_model=ResponseBase)
async def batch_confirm_issues(
    issue_ids: List[int] = Body(..., description="问题ID列表"),
    confirm_type: str = Body(..., description="确认类型"),
    confirmed_by: str = Body(..., description="确认人"),
    confirm_comment: Optional[str] = Body(None, description="确认备注"),
    db: Session = Depends(get_db),
):
    """批量确认问题"""
    service = IssueService(db)
    confirmed_issues = service.batch_confirm(
        issue_ids=issue_ids,
        confirm_type=confirm_type,
        confirmed_by=confirmed_by,
        confirm_comment=confirm_comment,
    )

    # 获取扩展字段数据
    issue_responses = []
    for issue in confirmed_issues:
        issue_dict = IssueResponse.from_orm(issue).dict()
        extensions = service.get_extensions(issue.id)
        issue_dict["extension_data"] = extensions if extensions else None
        issue_responses.append(IssueResponse(**issue_dict))

    return ResponseBase(
        code=200,
        message=f"成功确认 {len(confirmed_issues)} 个问题",
        data=issue_responses,
    )

